/**
 * @Author: jipeng.Li
 * @Date: 2021-04-20 08:22:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-04-20 11:54:21
 * @Description: 共享记录
 */

import React, { Component } from 'react';
import {
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View } from 'react-native';
import {
  fontColorBlack,
  fontColorCoffee,
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp,
  splitLineColorLightGray
} from '@/styles';
import LinearGradient from 'react-native-linear-gradient';
import DateTimePicker from 'react-native-modal-datetime-picker';
import Moment from 'moment';
import wlRepair from '@/api/repair';
import oil from '@/api/oil';
import { msg } from '@/common';
import SearchUserView from '../oil-card-platform/add-oil-authorize/components/search-user-view';
import {
  DateTimePickerCell,
  IsLimitInputCell,
  UserInfoCell
} from '../oil-card-platform/add-oil-authorize/components/authorize-set-up-cell';

export default class ShareAuthorize extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showDateTimePicker: false, // 是否显示日期选择
      step: 0,
      phoneNumber: '', // 手机号
      deadline: '', // 截至日期
      isLimitNumber: false, // 是否限制次数
      limitNumber: '', // 限制次数
      isQuota: false, // 是否限制金额
      authBalance: '', // 限制金额
      cardData: '', // 分享的油卡id 通过路由获取
      userData: {}, // 手机号查询出的用户数据
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { cardData } = params;
    this.setState({ cardData }, () => {

    });
  }

  stepViews = {
    0: 'renderSearchUserView',
    1: 'renderAuthorizeSetUpView'
  }

  render() {
    const { step, phoneNumber, showDateTimePicker } = this.state;
    return (
      <SafeAreaView
        style={[
          styles.container,
          { backgroundColor: step ? mainBgColorLightGray : mainBgColorWhite }
        ]}
      >
        <ScrollView style={{ flex: 1, }}>
          {this[this.stepViews[step]]()}
          <View style={{ alignItems: 'center' }}>
            <TouchableOpacity
              activeOpacity={0.8}
              disabled={!step && !phoneNumber}
              onPress={this.nextStep}
              style={[styles.nextStepBtn, (!step && !phoneNumber) && { opacity: 0.5 }]}
            >
              <Text style={styles.nextStepBtnText}>{step ? '确认授权' : '下一步'}</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>
        <DateTimePicker
          isVisible={showDateTimePicker}
          mode='date'
          cancelTextIOS='取消'
          confirmTextIOS='确认'
          headerTextIOS='选取日期'
          locale='zh_CN'
          onConfirm={date => {
            this.setState({ showDateTimePicker: false });
            this.dataPickerConfirm(date);
          }}
          onCancel={() => this.setState({ showDateTimePicker: false })}
        />
        {this.renderTipsView()}
      </SafeAreaView>
    );
  }

  // 底部提示
  renderTipsView = () => {
    const { step } = this.state;
    return (
      <View style={styles.tipsContainer}>
        <View style={styles.tipsTitle}>
          <LinearGradient
            colors={['#E5B867', '#BB934B']}
            style={styles.tipsFlag}
          />
          <Text style={styles.tipsTitleText}>温馨提示：</Text>
        </View>
        {
          step ? (
            <>
              <Text style={styles.tipsText}>到达截止日期24时，维修卡将自动收回；到达限制次数，维修卡将自动收回；</Text>
            </>
          ) : (
            <Text style={styles.tipsText}>
              您可将修理卡分享至其他已实名认证的司机共同使用；勿将修理卡授权给无关司机使用，产生的后果自行承担责任，授权到期后，自动停止授权；
            </Text>
          )
        }
      </View>
    );
  }

  // 手机号查询用户
  renderSearchUserView = () => {
    const { phoneNumber } = this.state;
    return (
      <SearchUserView
        placeholder='请输入获取维修卡用户的手机号'
        phoneNumber={phoneNumber}
        onChangeText={number => {
          const newNumber = number.replace(/[^\d]+/, '');
          this.setState({ phoneNumber: newNumber });
        }}
      />
    );
  }

  // 授权设置页面
  renderAuthorizeSetUpView = () => {
    const { deadline, isLimitNumber, limitNumber, isQuota, authBalance, userData } = this.state;
    return (
      <View style={{ marginBottom: px2dp(80) }}>
        <View style={styles.authorizeSetUpContainer}>
          <UserInfoCell title='手机号' value={userData.mobile} />
          <UserInfoCell title='姓名' value={userData.name} />
          <UserInfoCell title='车牌号' value={userData.carNo} />
        </View>
        <View style={styles.authorizeSetUpContainer}>
          <DateTimePickerCell
            deadline={deadline}
            onClick={() => this.setState({ showDateTimePicker: true })}
          />
          <IsLimitInputCell
            title='限制次数'
            noLimitText='不限制次数使用'
            placeholder='请输入最大核销次数'
            unit='次'
            isLimit={isLimitNumber}
            limitValue={limitNumber}
            switchChange={value => {
              if (!value) {
                this.setState({ limitNumber: '' });
              }
              this.setState({ isLimitNumber: value });
            }}
            textChange={value => {
              let newNumber = value;
              // obj.value = obj.value.replace(/[^\d]/g, "");//清除“数字“以外的字符
              if (newNumber.length == 1) {
                newNumber = newNumber.replace(/[^1-9]/g, '');
              } else {
                newNumber = newNumber.replace(/\D/g, '');
              }
              newNumber = newNumber.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');// 替换调其他字母或者.等
              this.setState({ limitNumber: newNumber });
            }}
          />
        </View>
      </View>
    );
  }

  dataPickerConfirm = (date) => {
    let currDate = new Date();
    let differentDate = (date - currDate) + 24 * 3600 * 1000;
    if (differentDate < 0) {
      msg.emit('app:tip', { text: '截止日期不能早于当前' });
    } else {
      this.setState({
        deadline: Moment(date).format('YYYY-MM-DD'),
        showDateTimePicker: false
      });
    }
  }

  // 下一步
  nextStep = () => {
    const { step } = this.state;
    if (!step) {
      this.getDriverByPhone();
    } else {
      this.ownerAuthorization();
    }
  }

  /**
   * 接口
   */
  getDriverByPhone = () => {
    const { phoneNumber, cardData } = this.state;
    oil.getDriverByPhone({ phone: phoneNumber, legalCustId: cardData.legalCustId }).then(res => {
      if (res.success) {
        if (res.data) {
          this.setState({ userData: res.data, step: 1 });
        } else {
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '提示',
            text: '用户未注册或未实名',
            okText: '确定',
            isClickBg: false,
          });
        }
      } else {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '提示',
          text: res.msg,
          okText: '确定',
          isClickBg: false,
        });
      }
    });
  }

  ownerAuthorization() {
    const {
      deadline,
      isLimitNumber,
      limitNumber,
      cardData,
      userData,
      isQuota,
      authBalance
    } = this.state;
    if (!deadline) {
      msg.emit('app:tip', { text: '请输入截至日期' });
      return;
    }
    if (isLimitNumber && !limitNumber) {
      msg.emit('app:tip', { text: '请输入限制次数' });
      return;
    }

    wlRepair.ownerAuthorization({
      accountCarownerId: cardData.accountCarownerId,
      carNo: userData.carNo,
      driverCustId: userData.custId,
      empowerEndTime: `${deadline} 23:59:59`,
      empowerNum: limitNumber,
      isLimit: isLimitNumber ? 'Y' : 'N',
      isQuota: isQuota ? 'Y' : 'N',
      authBalance,
      empowerStartTime: Moment(new Date()).format('YYYY-MM-DD hh:MM:ss')
    }).then(res => {
      if (res.success) {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '提示',
          text: '授权成功，您可通过授权记录收回维修卡授权。',
          okText: '确定',
          isClickBg: false,
          okFn: () => {
            msg.emit('router: refreshRoute', {
              routeName: 'WlRepairShareRecord',
            });
            msg.emit('router: back');
          },
        });
      } else {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '提示',
          text: res.msg || '授权失败',
          okText: '确定',
          isClickBg: false,
        });
      }
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },

  phoneNumberWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    borderRadius: px2dp(12),
    paddingHorizontal: px2dp(10)
  },
  phoneNumber: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    color: fontColorBlack,
  },
  authorizeSetUpContainer: {
    marginTop: px2dp(30),
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(30),
  },
  authorizeCell: {
    borderBottomWidth: px2dp(1),
    borderBottomColor: '#F0F0EF',
    flexDirection: 'row',
    alignItems: 'center',
    height: px2dp(102)
  },
  tipsContainer: {
    height: px2dp(200),
    justifyContent: 'center',
    borderTopWidth: px2dp(1),
    borderTopColor: splitLineColorLightGray,
    marginHorizontal: px2dp(50)
  },
  tipsFlag: {
    width: px2dp(6),
    height: px2dp(24),
    marginRight: px2dp(10)
  },
  tipsTitle: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  tipsTitleText: {
    fontSize: px2dp(28),
    color: fontColorBlack,
    fontWeight: 'bold'
  },
  tipsText: {
    color: '#686764',
    fontSize: px2dp(28),
  },
  nextStepBtn: {
    width: px2dp(640),
    height: px2dp(88),
    backgroundColor: fontColorCoffee,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: px2dp(12)
  },
  nextStepBtnText: {
    color: mainBgColorWhite,
    fontSize: px2dp(32)
  }
});
